package com.xinggq.common.utils;

/**
 * @Description
 * @Author xinggq
 * @Date 2024/9/26
 */
public class HexUtils {

  private HexUtils() {
  }

  private static final char[] DIGITS = "0123456789ABCDEF".toCharArray();


  /**
   * 高效写法 byte数组转成16进制字符串
   *
   * @param bytes byte数组
   * @return 16进制字符串
   */
  public static String bytesToHexString(byte[] bytes) {
    char[] buf = new char[bytes.length * 2];
    int c = 0;
    for (byte b : bytes) {
      buf[c++] = DIGITS[(b >> 4) & 0x0F];
      buf[c++] = DIGITS[b & 0x0F];
    }
    return new String(buf);
  }


  /**
   * 高效写法 16进制字符串转成byte数组
   *
   * @param hex 16进制字符串，支持大小写
   * @return byte数组
   */
  public static byte[] hexStringToBytes(String hex) {
    byte[] result = new byte[hex.length() / 2];
    char[] chars = hex.toCharArray();
    for (int i = 0, j = 0; i < result.length; i++) {
      result[i] = (byte) (toByte(chars[j++]) << 4 | toByte(chars[j++]));
    }
    return result;
  }

  private static int toByte(char c) {
    if (c >= '0' && c <= '9') {
      return (c - '0');
    }
    if (c >= 'A' && c <= 'F') {
      return (c - 'A' + 0x0A);
    }
    if (c >= 'a' && c <= 'f') {
      return (c - 'a' + 0x0a);
    }
    throw new RuntimeException("invalid hex char '" + c + "'");
  }


}
